package nl.grol.yakshop.commandLine;

import java.io.InputStream;

import nl.grol.yakshop.dataimporter.HerdImporterI;
import nl.grol.yakshop.dataimporter.XmlHerdImporter;
import nl.grol.yakshop.domain.model.YakHerd;
import nl.grol.yakshop.domain.model.YakI;
import nl.grol.yakshop.domain.service.BruteForceProducionCalculator;
import nl.grol.yakshop.domain.service.ProductionCalculatorI;
import nl.grol.yakshop.util.ConversionUtil;
import nl.grol.yakshop.util.InvalidInputException;
import nl.grol.yakshop.util.YakShopException;

public final class CommandLineTool {

	private CommandLineTool() {
	}
	
	public static void main(String[] args) throws YakShopException {
		try {
			
			/*
			 * Parse command-line arguments
			 */
			if (args.length != 2) {
				throw new InvalidInputException("Invalid number of command-line parameters");
			}
			String xmlFilename = args[0];
			Integer daySinceStartOfShop = ConversionUtil.stringToNonNegativeInt( args[1] );

			/*
			 * Read herd from xml-file
			 */
			HerdImporterI importer = new XmlHerdImporter();
			InputStream is = CommandLineTool.class.getClassLoader().getResourceAsStream(xmlFilename);
			YakHerd herd = importer.loadFromInputStream(is);
			
			/*
			 * Calculate stock
			 */
			ProductionCalculatorI calculator = new BruteForceProducionCalculator();
			double totalMilkInStock = calculator.calculateHerdMilkProductionSofar(herd.getYaks(), daySinceStartOfShop);
			int totalSkinsInStock = calculator.calculateHerdSkinProductionSofar(herd.getYaks(), daySinceStartOfShop);

			/*
			 * Report result to screen
			 */
			writeResultToStdout(totalMilkInStock, totalSkinsInStock, 
					herd, daySinceStartOfShop);

		} catch( InvalidInputException exc ) {
			
			System.err.println("Usage: CommandLineTool <herd.xml-file> <days-since-shop-opening>");
			System.err.println("Details:" + exc.getMessage() );
			
		} catch( YakShopException exc ) {
			
			System.err.println("Error reading xml-file with name " + args[0] +
					" (" + exc.getMessage() + ")" );
			
		}
	}
	
	private static void writeResultToStdout( double totalMilkInStock,
											 int totalSkinsInStock,
											 YakHerd herd,
											 int daySinceStartOfShop) {

		System.out.println("Output for T = " + daySinceStartOfShop + ":");

		System.out.println("");

		System.out.println("In Stock:");
		System.out.println("\t" + ConversionUtil.format3(totalMilkInStock)	+ " liters of milk");
		System.out.println("\t" + totalSkinsInStock + " skins of wool");

		System.out.println("Herd:");
		for (YakI yak : herd.getYaks()) {
			System.out.println("\t" + yak.getName() + " "
					+ ConversionUtil.format2(yak.getAgeInYearsOnDay(daySinceStartOfShop))
					+ " years old");
		}

		System.out.println("");
	}
}
